package cn.ven.service;

import cn.ven.entity.Focus;
import cn.ven.entity.FocusUser;
import cn.ven.entity.MyUser;
import cn.ven.mapper.FocusMapper;
import cn.ven.tool.SessionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class FocusServieImpl implements FocusService {

    @Autowired(required = false)
    FocusMapper focusMapper;

    @Autowired
    UserService userService;

    @Override
    public int addFocus(Focus focus) {
        LambdaQueryWrapper<Focus> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Focus::getFocuseduid,focus.getFocuseduid());
        queryWrapper.eq(Focus::getUid,SessionUtil.getId());
        Focus focus1 = focusMapper.selectOne(queryWrapper);
        if (focus1==null){ //判断是否以已经关注过了
            focus.setUid(SessionUtil.getId());
            focusMapper.insert(focus);//添加关注
            MyUser myUser = userService.findById(SessionUtil.getId()); //用户自己
            myUser.setFocusNum(myUser.getFocusNum()+1); //关注数+1
            userService.updateUser(myUser);

            MyUser focusedUser = userService.findById(focus.getFocuseduid()); //被关注的用户
            focusedUser.setFocusedNum(focusedUser.getFocusedNum()+1); //被关注+1
            userService.updateUser(focusedUser);
            return 1;
        }
        return 0;
    }

    @Override
    public int cancelFocus(int uid) {
        LambdaQueryWrapper<Focus> queryWrapper =new LambdaQueryWrapper();
        queryWrapper.eq(Focus::getUid,SessionUtil.getId());
        queryWrapper.eq(Focus::getFocuseduid,uid);
        Focus focus = focusMapper.selectOne(queryWrapper);
        if (focus!=null){
            focusMapper.deleteById(focus);
            MyUser myUser = userService.findById(SessionUtil.getId()); //用户自己
            myUser.setFocusNum(myUser.getFocusNum()-1);//关注数-1
            userService.updateUser(myUser);

            MyUser focusedUser = userService.findById(focus.getFocuseduid());//被关注的用户
            focusedUser.setFocusNum(focusedUser.getFocusedNum()-1);//关注数-1
            userService.updateUser(focusedUser);
            return 1;
        }
        return 0;
    }

    @Override
    public List<FocusUser> findAllFocusedUser(int focusedUid) {
        List<FocusUser> focusedUsers = focusMapper.findAllFocusedUser(SessionUtil.getId(), focusedUid);
        return focusedUsers;
    }

    @Override
    public List<FocusUser> findAllFocusUser() {
        List<FocusUser> focusUsers = focusMapper.findAllFocusUser(SessionUtil.getId());
        return focusUsers;
    }


}
